/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package VISUAL;
import DAL.ConectaBd;
import java.sql.*;
import javax.swing.ComboBoxModel;
import javax.swing.JOptionPane;
import net.proteanit.sql.DbUtils;

/**
 *
 * @author MAYCON
 */
public class frmContasaReceber extends javax.swing.JInternalFrame {
    Connection con = null;
    Connection conecta;
    PreparedStatement pst;
    ResultSet rs;

    /**
     * Creates new form frmContasaReceber
     */
    public frmContasaReceber() throws ClassNotFoundException {
        initComponents();
        this.setLocation(450,100);
        conecta = ConectaBd.conectabd();
        con = ConectaBd.conectabd();
        this.PopulacomboboxClienteEscolha();
        ListarRecebimentos();
    }
    
    public void ListarRecebimentos()//Método para aparecer na tabela os dados das contas a pagar
    {
        String sql = "Select *from receber order by id Asc";// order by codigo Asc para deixar em ordem por código crescente
        try
        {
            pst = conecta.prepareStatement(sql);
            rs = pst.executeQuery();
            tblReceber.setModel(DbUtils.resultSetToTableModel(rs));
            
        }
        catch(SQLException error)
        {
            JOptionPane.showMessageDialog(null,error);
        }    
    }
    
    public void PesquisarRecebimentos()//Método a qual irá funcionar o campo pesquisar
    {
        String sql = "Select *from receber where cliente like ?";
        
        try
        {
            pst = conecta.prepareStatement(sql);
            pst.setString(1,txtPesquisa.getText()+"%");
            rs = pst.executeQuery();
            tblReceber.setModel(DbUtils.resultSetToTableModel(rs));
            
        }
        catch(SQLException error)
        {
            JOptionPane.showMessageDialog(null,error);
        }    
    }
    
    public void CadastrarRecebimentos()//metodo para funcionar o cadastro de usuários no botão cadastrar
    {
        String sql = "Insert into receber (cliente,vencimento,tipo,nnota,obs,valor)values(?,?,?,?,?,?)";
        try
        {
            pst = conecta.prepareStatement(sql);
            pst.setString(1, (String) jComboBoxCliente.getSelectedItem());
            pst.setString(2,txtVencimento.getText());
            pst.setString(3, (String) jComboBoxTipo.getSelectedItem());
            pst.setString(4,txtNota.getText());
            pst.setString(5,txtObs.getText());
            pst.setString(6,txtValor.getText());;
            
            
            
            pst.execute();
            JOptionPane.showMessageDialog(null, "Recebimento cadastrado com sucesso","Recebimento cadastrado com sucesso",JOptionPane.INFORMATION_MESSAGE);
            ListarRecebimentos();
        }
        catch (SQLException error)
        {
            JOptionPane.showMessageDialog(null, error);
        }
    }
    
    public void PopulacomboboxClienteEscolha()
    {
        String sql = "select cadcliente.nome, tipoderecebimento.tipo from cadcliente,tipoderecebimento ";
            
        
        
        try
        {
            pst = con.prepareStatement(sql);
            rs = pst.executeQuery();
                    
            while(rs.next())
            {
                jComboBoxCliente.addItem(rs.getString("nome"));
                jComboBoxTipo.addItem(rs.getString("tipo"));
                
            }
            
        }catch(SQLException ex)
        {
            JOptionPane.showMessageDialog(null, ex);
        }
    }
    
    public void ComboboxContas()
    {
        String sql = "select nome from cadcliente as A join tipoderecebimento as tipo(nome.chaveEstrangeiraQueApontaParatipoderecebimento = tipoderecebimento.chavePrimaria)";
        
        
        
        try
        {
            pst = con.prepareStatement(sql);
            pst.setString(1, (String) jComboBoxCliente.getSelectedItem());
            pst.setString(2, (String) jComboBoxTipo.getSelectedItem());
            
            
            rs = pst.executeQuery();
            
        }
        catch(SQLException error)
        {
            JOptionPane.showMessageDialog(null, error);
        }    
    }
    
    public void LimparCamposReceber()//metodo para funcionar o botão limpar ao clica-lo
    {
        txtId.setText("");
        txtVencimento.setText("");
        txtNota.setText("");
        txtObs.setText("");
        txtValor.setText("");    
        
    }
    
    public void MostrarReceber()//Este metodo ao clicar no cheque irá mostrar nos campos todas informações cadastradas, utilizado para deletar e editar
    {
        int seleciona = tblReceber.getSelectedRow();
        txtId.setText(tblReceber.getModel().getValueAt(seleciona,0).toString());
        //jComboBoxFornecedor.setText(tblcontas.getModel().getValueAt(seleciona,1).toString()); deixei em em comentário pois talvez ñ use
        txtVencimento.setText(tblReceber.getModel().getValueAt(seleciona,2).toString());
        //jComboBoxTipo.setText(tblcontas.getModel().getValueAt(seleciona,3).toString());
        txtNota.setText(tblReceber.getModel().getValueAt(seleciona,4).toString());
        txtObs.setText(tblReceber.getModel().getValueAt(seleciona,5).toString());
        txtValor.setText(tblReceber.getModel().getValueAt(seleciona,6).toString());
           
        
    }
    
    public void AtualizarRecebimento()//Este método excluir o cheque após clicado na opção delete
    {
        String sql =  "Update receber set cliente = ?,vencimento = ?,tipo = ?,nnota = ?,obs = ?,valor = ? where id = ?";
        
        try
        {
            pst = conecta.prepareStatement(sql);
            pst.setString(1, (String) jComboBoxCliente.getSelectedItem());
            pst.setString(2,txtVencimento.getText());
            pst.setString(3, (String) jComboBoxTipo.getSelectedItem());
            pst.setString(4,txtNota.getText());
            pst.setString(5,txtObs.getText());
            pst.setString(6,txtValor.getText());
            pst.setInt(7,Integer.parseInt(txtId.getText()));
            pst.executeUpdate();
            JOptionPane.showMessageDialog(null,"Recebimento atualizado com sucesso");
            LimparCamposReceber();
        }
        catch (SQLException error)
        {
            JOptionPane.showMessageDialog(null, error);
        }    
    }
    
    public void DeletarRecebimento()
    {
        String sql = "Delete from receber where id = ?";//Metodo para exclusão de conta pelo botão
        
        try
        {
            pst = conecta.prepareStatement(sql);
            pst.setInt(1,Integer.parseInt(txtId.getText()));
            pst.execute();
            ListarRecebimentos();
        }
        catch(SQLException error)
        {
            JOptionPane.showMessageDialog(null,error);
            
            
        }
    }
    
    
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jComboBoxCliente = new javax.swing.JComboBox();
        jComboBoxTipo = new javax.swing.JComboBox();
        txtVencimento = new javax.swing.JFormattedTextField();
        jLabel4 = new javax.swing.JLabel();
        txtId = new javax.swing.JTextField();
        jLabel5 = new javax.swing.JLabel();
        txtNota = new javax.swing.JTextField();
        jLabel6 = new javax.swing.JLabel();
        txtValor = new javax.swing.JTextField();
        txtObs = new javax.swing.JTextField();
        jLabel7 = new javax.swing.JLabel();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jButton4 = new javax.swing.JButton();
        jButton3 = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        tblReceber = new javax.swing.JTable();
        txtPesquisa = new javax.swing.JTextField();
        jLabel11 = new javax.swing.JLabel();

        setClosable(true);
        setIconifiable(true);
        setTitle("Contas a Receber");
        setPreferredSize(new java.awt.Dimension(720, 510));

        jLabel1.setText("Cliente");

        jLabel2.setText("Data Vencimento");

        jLabel3.setText("Tipo");

        try {
            txtVencimento.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("##/##/####")));
        } catch (java.text.ParseException ex) {
            ex.printStackTrace();
        }

        jLabel4.setText("Id");

        txtId.setEnabled(false);

        jLabel5.setText("Nº Nota");

        jLabel6.setText("Valor");

        jLabel7.setText("Obs");

        jButton1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/ICONES/disk.png"))); // NOI18N
        jButton1.setText("Cadastrar");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jButton2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/ICONES/arrow_refresh.png"))); // NOI18N
        jButton2.setText("Atualizar");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jButton4.setIcon(new javax.swing.ImageIcon(getClass().getResource("/ICONES/delete.png"))); // NOI18N
        jButton4.setText("Limpar");
        jButton4.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton4ActionPerformed(evt);
            }
        });

        jButton3.setIcon(new javax.swing.ImageIcon(getClass().getResource("/ICONES/cancel.png"))); // NOI18N
        jButton3.setText("Deletar");
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });

        tblReceber.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        tblReceber.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                tblReceberMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(tblReceber);

        txtPesquisa.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                txtPesquisaKeyReleased(evt);
            }
        });

        jLabel11.setIcon(new javax.swing.ImageIcon(getClass().getResource("/ICONES/zoom.png"))); // NOI18N
        jLabel11.setText("BUSCAR");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane1)
            .addGroup(layout.createSequentialGroup()
                .addComponent(txtPesquisa)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jLabel11)
                .addContainerGap())
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel2)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(txtVencimento, javax.swing.GroupLayout.PREFERRED_SIZE, 154, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(10, 10, 10)
                                .addComponent(jLabel3)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jComboBoxTipo, javax.swing.GroupLayout.PREFERRED_SIZE, 202, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel7)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(txtObs, javax.swing.GroupLayout.PREFERRED_SIZE, 439, javax.swing.GroupLayout.PREFERRED_SIZE)))
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel6)
                                .addGap(18, 18, 18)
                                .addComponent(txtValor, javax.swing.GroupLayout.DEFAULT_SIZE, 130, Short.MAX_VALUE))
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel5)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(txtNota)))
                        .addContainerGap())
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel4)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(txtId, javax.swing.GroupLayout.PREFERRED_SIZE, 48, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel1)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jComboBoxCliente, javax.swing.GroupLayout.PREFERRED_SIZE, 202, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addComponent(jButton1)
                            .addComponent(jButton2)
                            .addComponent(jButton4)
                            .addComponent(jButton3))
                        .addGap(0, 0, Short.MAX_VALUE))))
        );

        layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {jButton1, jButton2, jButton3, jButton4});

        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(txtId, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(jComboBoxCliente, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(txtVencimento, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel3)
                    .addComponent(jComboBoxTipo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel5)
                    .addComponent(txtNota, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtValor, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel6)
                    .addComponent(txtObs, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel7))
                .addGap(33, 33, 33)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jButton4)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jButton1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButton2)
                        .addGap(30, 30, 30)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jButton3)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 14, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtPesquisa, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel11))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 182, javax.swing.GroupLayout.PREFERRED_SIZE))
        );

        layout.linkSize(javax.swing.SwingConstants.VERTICAL, new java.awt.Component[] {jButton1, jButton2, jButton3, jButton4});

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        // Este é o botão cadastro do cheque, e ele está chamando o método :
        CadastrarRecebimentos();
    }//GEN-LAST:event_jButton1ActionPerformed

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        // Este é o botão do atualizar, ele irá chamar o método:
        AtualizarRecebimento();
    }//GEN-LAST:event_jButton2ActionPerformed

    private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed
        // Botão com método para limpar dados dos campos contas:
        LimparCamposReceber();
    }//GEN-LAST:event_jButton4ActionPerformed

    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
        // Botão com método para deletar fornecedor:
        DeletarRecebimento();
    }//GEN-LAST:event_jButton3ActionPerformed

    private void txtPesquisaKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtPesquisaKeyReleased
        // TODO add your handling code here:
        PesquisarRecebimentos();
    }//GEN-LAST:event_txtPesquisaKeyReleased

    private void tblReceberMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tblReceberMouseClicked
        // TODO add your handling code here:
        MostrarReceber();
    }//GEN-LAST:event_tblReceberMouseClicked


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JButton jButton4;
    private javax.swing.JComboBox jComboBoxCliente;
    private javax.swing.JComboBox jComboBoxTipo;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel11;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable tblReceber;
    private javax.swing.JTextField txtId;
    private javax.swing.JTextField txtNota;
    private javax.swing.JTextField txtObs;
    private javax.swing.JTextField txtPesquisa;
    private javax.swing.JTextField txtValor;
    private javax.swing.JFormattedTextField txtVencimento;
    // End of variables declaration//GEN-END:variables
}
